{% include 'header.html' %}

  <title>Wox Status: {{dj_title}}</title>
  <link href="{{ STATIC_URL }}css/validationEngine.jquery.css" rel="stylesheet" type="text/css">
{% if dj_has_searchform %}
  <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.validationEngine.js"></script>
  <script type="text/javascript" src="{{ STATIC_URL }}js/jquery.validationEngine-en.js"></script>
  <script type="text/javascript" src="{{ STATIC_URL }}js/mustache.js"></script>
  <script type="text/javascript" src="{{ STATIC_URL }}js/jquery-Mustache.js"></script>
{% endif %}

  {% load socketio_tags %}
  {% socketio %}
  <script type="text/javascript"> 

{% if dj_has_searchform %}
    function csrfSafeMethod(method) {
        // these HTTP methods do not require CSRF protection
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

    function showLoading(obj) {
        if (obj) {
            var nextobj = obj.next('.field-indic');
            if (nextobj)
                nextobj.attr('class', 'field-indic loading-indicator');
        }
    }

    function endLoading(obj) {
        if (obj) {
            var nextobj = obj.next('.field-indic');
            if (nextobj)
                nextobj.attr('class', 'field-indic');
        }
    }

    Mustache.tags = ['[[', ']]'];      
    var csrftoken = getCookie('csrftoken');

    var mgroup_change_flag = false;

    function get_dashboard() {
        var container = $('#div_dashboard');
        $('#form_dashboard').ajaxSubmit({
            dataType: 'json',
            beforeSerialize:function() {
                if (! $('#form_dashboard').validationEngine('validate')) {
                    return false;
                }
            },
            success:function(r) {
                mgroup_change_flag = false;
                // the loading img is not present if use empty()
                container.html('<br>');
                container.attr('class', 'loading-indicator');    
                setTimeout(function() {
                    container.attr('class', '');    
		    // if sel_build doesn't exist, create it
		    if ($('#sel_build').length == 0) {
                        $('#tr_build').mustache(
                            'tr_build_tmpl', 
                            {m_builds: r.builds,
                             'm_builds_len?': r.builds ? r.builds.length : null},
                            {method: 'html'});
			// make sure the first option is selected
			$("#sel_build option:first").attr('selected','selected');
		    }
                    container.html(r.dbhtml);
                    // trigger status tracking magic
                    magic_init();
                }, 500);
            },
            error:function() {
                alert("get dashboard failed!");
            }
        });  // end of ajaxSubmit
    }

{% endif %}

    /*
     * block for status tracking
     */
    /* global variables */
    // test status
    var tstatus = {};
    // to make sure just sync once
    var firstsync_flag = false;
    // test raw log dir
    var rlogdirs = {};
    // testopia run ids
    var testopia_runids = {};


    /* count json object length */
    function getlen(jsonobj) {
        var l = 0;
        for (i in jsonobj)
            l++;
        return l;
    }

    /* get completion report */
    function get_creport() {
        crpt_container =  $('#completion_report');
        crpt_container.html('<br>');
        crpt_container.attr('class', 'loading-indicator-center');

        $.ajax({
            type: 'post',
            url: '{% url ajax_getcreport %}',
            dataType: 'json',
            data: {testopia_runids: JSON.stringify(testopia_runids),
                   hid_tcn_guess: $('#hid_tcn_guess').val()},
            crossDomain: false,
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type)) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            },
            success: function(r) {
                crpt_container.attr('class', '');
                crpt_container.html(r.report_html);
            },
            error: function() {
                crpt_container.attr('class', '');
                alert("get completion report failed!");
            }
        }); // end of ajax
    }

    function magic_init() {
        // check if dashboard table is present
        if (!$('#hid_runrpt_url').val()) {
            return;
        }

        // reset global variables
        tstatus = {};
        firstsync_flag = false;
        rlogdirs = {};
        testopia_runids = {};

        var update_crpt_flag = false;
        // initialize global variables for status tracking
        $('.testgroup').each(function() {
            var gid = $(this).attr('id');
            $(this).find('.woxst-sum-bar').each(function() {
                var id = $(this).attr('id');
                var s = $(this).html();
    
                // check test status here
                switch (s) {
                    case 'error':
                    case 'terminated':
                    case 'timeout':
                    case 'cancelled':
                    case 'finished':
                        break;
                    case 'scheduled':
                    case 'started':
                    case 'na':
                        if (!(gid in tstatus)) {
                            tstatus[gid] = {};
                        }
                        firstsync_flag = true;
                        tstatus[gid][id] = s;
                        break;
                }
                var rlogdir = $('#' + id + '-logdir').val();
                if (rlogdir) {
                    rlogdirs[id] = rlogdir;
                }
                var trunid = $('#' + id + '-runid').val();
                if (trunid) {
                    testopia_runids[id] = trunid;
                    update_crpt_flag = true;
                }
    
            }); // end of each bar
        }); // end of each testgroup
        if (update_crpt_flag) {
            get_creport();
        }

        magic();
    } // end of magic_init

    function magic() {
        // will be instanced in start()
        var socket;
    
        var connected = function() {
            // use testgroup id as group channel name
            // use status bar id as channel name
            for (g in tstatus) {
                socket.subscribe(g);
            }

            // just sync once
            if (firstsync_flag && getlen(tstatus)) {
                firstsync_flag = false;
                socket.send({channelgroups: tstatus});
            }
        };
    
        var disconnected = function() {
            // reconnect after 1s
            setTimeout(start, 1000);
        };
    
        var messaged = function(data_array) {
          // update completion report flag
          var update_crpt_flag = false;
          $.each(data_array, function(i, data) {
              var c = data.channel;
              var natrid = data.natrid;
  
              // testrun available now flag
              var tran_flag = false;
              var gid = '';
              for (g in tstatus) {
                  if (c in tstatus[g]) {
                      gid = g;
                      break;
                  } else if (natrid in tstatus[g]) {
                      gid = g;
                      tran_flag = true;
                      tstatus[g][c] = tstatus[g][natrid];
                      delete tstatus[g][natrid];
                      $('#' + natrid).attr('id', c);
                      break;
                  } 
              }
              if (!gid) {
                  // continue
                  return;
              }
                
              var s = data.status;
              if (tstatus[gid][c] != s) {
                  tstatus[gid][c] = s;
                  switch (s) {
                      case 'error':
                      case 'terminated':
                      case 'timeout':
                      case 'cancelled':
                      case 'finished':
                          socket.unsubscribe(c);
                          delete tstatus[gid][c];
                          if (!getlen(tstatus[gid])) {
                              delete tstatus[gid];
                          }
                          break;
                  }
  
                  // resetting title bar class value to change the color
                  var woxs_bar = $('#' + c);
                  woxs_bar.attr('class', 'woxst-sum-bar loading-indicator-center');
                  setTimeout(function() { 
                      woxs_bar.attr('class', 'woxst-sum-bar woxst_' + s);
                      woxs_bar.html(s);
                  }, 500);
              }
  
              // record the raw log dir
              if (data.rlogdir && !(c in rlogdirs)) {
                  rlogdirs[c] = data.rlogdir;
              }
              // record testopia run id
              if (data.trunid && !testopia_runids[c]) {
                  // record run id as string
                  testopia_runids[c] = data.trunid + '';
                  update_crpt_flag = true;
              }
          }); // end of each

          // update completion report if necessary
          if (update_crpt_flag) {
              get_creport();
          }
          
        }; // end of messaged
    
        var start = function() {
            socket = new io.Socket();
            socket.connect();
            socket.on('connect', connected);
            socket.on('disconnect', disconnected);
            socket.on('message', messaged);
        };
    
        start();
    } // end of magic()
    /* end of status tracking block */

    $(document).ready(function() {

{% include 'topnav-imd.js' %}

{% if dj_has_searchform %}
        $('#form_dashboard').validationEngine('attach', {scroll: false});
        $('body').mousemove(function() {
            $('#form_dashboard').validationEngine('hideAll');
        });

        $.Mustache.addFromDom('tr_mgroup_tmpl', 'tr_build_tmpl');

        $('#sel_os_release').change(function() { 
            var sel_osr = $(this);

            if (!sel_osr.val()) {
                return;
            }

            $('.plugable').remove();
            $('#div_dashboard').html('<br>');

            $.ajax({
                type: 'post',
                url: '{%url ajax_getdbmgrp %}',
                dataType: 'json',
                data: $('#form_dashboard').serializeArray(),
                crossDomain: false,
                beforeSend: function(xhr, settings) {
                    if (!csrfSafeMethod(settings.type)) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                    showLoading(sel_osr);
                },
                success: function(r) {
                    endLoading(sel_osr);
                    $('#tr_os_release').mustache(
                        'tr_mgroup_tmpl', 
                        {m_mgroups: r.mgroups, 
                         'm_mgroups_len?': r.mgroups ? r.mgroups.length : null}, 
                        {method: 'after'});
                    mgroup_change_flag = true;
                },
                error: function() {
                    endLoading(sel_osr);
                    alert("get machine group failed!");
                }
            }); // end of ajax
        }); // end of change

        $('#div_search').on('change', '#sel_mgroup', function(e) { 
            // e.preventDefault(); 
            if ($('#sel_mgroup').val()) {
                mgroup_change_flag = true;
            }
        });

        $('#div_search').on('change', '#sel_build', function(e) { 
            e.preventDefault(); 

            if (!$('#sel_build').val()) {
                return;
            }
            get_dashboard(); 

        }); // end of on

        $('#div_search').on('click', '#btn_showdb', function(e) { 
            e.preventDefault(); 

            if (!mgroup_change_flag) {
                return;
            }
            get_dashboard(); 

        }); // end of on
{% endif %}

        magic_init();

    }); // end of ready
  </script>
{% if dj_has_searchform %}
  <script id="tr_mgroup_tmpl" type="text/html">
    [[#m_mgroups_len?]]
    <tr class="plugable">
      <td class="th-label">Machine Group:</td>
      <td><select multiple id="sel_mgroup" name="sel_mgroup" class="fixed-field validate[required]">
      [[#m_mgroups]]
        <option value="[[id]]" selected>[[name]]</option>
      [[/m_mgroups]]
      </select><span class="field-indic"></span>
    </td></tr>

    <tr class="plugable" id="tr_build"></tr>

    <tr class="plugable">
      <td class="th-label"></td>
      <td><input id="btn_showdb" name="btn_showdb" type="button" value="Dashboard" style="margin-left: 10px;"/>
      <span class="field-indic"></span>
    </td></tr> 
    [[/m_mgroups_len?]]
  </script>

  <script id="tr_build_tmpl" type="text/html">
    [[#m_builds_len?]]
      <td class="th-label">Build:</td>
      <td><select id="sel_build" name="sel_build" class="fixed-field">
      [[#m_builds]]
        <option value="[[.]]" selected>[[.]]</option>
      [[/m_builds]]
      </select><span class="field-indic"></span>
    </td>
    [[/m_builds_len?]]
  </script>
{% endif %}
</head>

<body class="defect-opensolaris-org-bz">
{% include 'topnav.html' %}
<div>
  <table id="tabtitles" border="0" cellpadding="0" cellspacing="0">
  <tbody><tr>
    <td id="title">
    <p><font color="#FFFFFF">&nbsp;Report &raquo; {{dj_title}}</font></p>
    </td></tr>
  </tbody></table>
</div>

<div id="bugzilla-body" style="min-height: 450px;">

{% if dj_has_searchform %}
<form id="form_dashboard" method="POST" action="{% url dashboard %}">
<div id="div_search">
{% csrf_token %}
  <table border="0" align="left" class="bz_buglist">
     <tr id="tr_os_release">
      <td class="th-label">OS Release:</td>
      <td><select id="sel_os_release" name="sel_os_release" class="fixed-field">
      <option value=""></option>
    {% for r in dj_os_release_qs %}
      <option value="{{r.id}}">{{r.description}}</option>
    {% endfor %}
      </select><span class="field-indic"></span>
    </td></tr>
    
  </table>
</div>
<!-- end of div_search -->

<br>
<table class="bz_buglist" cellpadding="4" cellspacing="0" width="100%">
<tbody>
</tbody></table>
<div><br></div>
{% endif %}

<div id="div_dashboard">

{{dj_dbhtml}}

</div>
<!-- end of div_dashboard -->

{% if dj_has_searchform %}
</form>
{% endif %}

</div>
<!-- end of div bugzilla-body -->

{% include 'footer.html' %}

